const db = wx.cloud.database()
const dataType = require('../../data/data')
const app=getApp()
Page({
  data: {
    list: dataType.minePage,
    avatarUrl: '',
    nickName: '无名氏',
    babaMinutes: '',
    babaTimes: '',
    avatatFileUrl: '',
    qianMing:'吃好喝好拉好'
  },

  navigatTo(e) {
    const index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: this.data.list[index].url,
    })
  },

  async userIsexist() {
    try {
      const userInfoResult = wx.getStorageSync('userInfoResult') || { data: [] }; // 设置默认值
      let openid = wx.getStorageSync('openid');
      if (!openid) {
        const res = await wx.cloud.callFunction({
          name: 'inquireUserInfo'
        });
        openid = res.result.openid;
      }
      const user = userInfoResult.data.find(item => item._openid === openid);
      if (user) {
        return { data: [user], userInfoResult, openid }; // 返回完整数据
      }
      return { data: [], userInfoResult, openid }; // 返回完整数据
    } catch (e) {
      console.error('检查用户存在失败:', e);
      return { data: [], userInfoResult: { data: [] }, openid: '' }; // 出错时返回默认值
    }
  },

  // async onShow() {
  //   const user = await this.userIsexist();
  //   this.calculation();
  //   if (this.data.nickName === '无名氏') {
  //     const userInfoResult = user.userInfoResult || { data: [] }; // 确保 userInfoResult 存在
  //     this.setData({
  //       nickName: `粑粑${userInfoResult.data.length >= 10 ? userInfoResult.data.length : '0' + userInfoResult.data.length}号`
  //     });
  //   }
  //   console.log(user);
  //   const record = {
  //     avatarUrl: this.data.avatarUrl,
  //     babaMinutes: this.data.babaMinutes,
  //     babaTimes: this.data.babaTimes,
  //     userId: 'sdsd',
  //     userName: this.data.nickName,
  //   };
  //   if (user.data.length == 0) {
  //     const existingUser = await db.collection('user').where({
  //       _openid: user.openid // 根据 openid 查询用户是否已存在
  //     }).get();
  //     if (existingUser.data.length == 0) { // 如果用户不存在，才插入记录
  //       db.collection('user').add({
  //         data: record,
  //         success: res => {
  //           console.log(res);
  //           let userInfoResult = wx.getStorageSync('userInfoResult') || { data: [] };
  //           userInfoResult.data.push(record);
  //           wx.setStorageSync('userInfoResult', userInfoResult);
  //         },
  //         fail: e => {
  //           console.log(e);
  //         }
  //       });
  //     }
  //   }
  // },

  calculation() {
    const dataBaseResult = wx.getStorageSync('dataBaseResult')
    let total = 0
    dataBaseResult.data.forEach(item => {
      total = total + Number(item.totalBaba)
    })
    this.setData({
      babaMinutes: total,
      babaTimes: dataBaseResult.data.length
    })
  },

  /**
   * @author 小锋
   * @param {string} avatarUrl chooseAvatar的用户头像地址（http://tmp）
   * @param {string} _openid 用户的openid 
   */
  upLoadAvatar(avatarUrl, _openid) {
    const date =new Date()
    const year=date.getFullYear()
    const month=date.getMonth()+1
    const day=date.getDate()
    const hour=date.getHours()
    const minute=date.getMinutes()
    const second=date.getSeconds()
    const formateMonth = month < 10 ? `0${month}` : `${month}`
    const formateDay = day < 10 ? `0${day}` : `${day}`
    const formateHour = hour < 10 ? `0${hour}` : `${hour}`
    const formateMinutes = minute < 10 ? `0${minute}` : `${minute}`
    const formateSecond = second < 10 ? `0${second}` : `${second}`

    wx.cloud.uploadFile({
      filePath: avatarUrl,
      name: 'userAvatar',
      cloudPath: `avatar/${_openid}-${year}-${formateMonth}-${formateDay} ${formateHour}:${formateMinutes}:${formateSecond}.jpg`,
      success: res => {
        console.log(res)
        this.getTempFileURL(res.fileID)
      }
    })
  },

  getTempFileURL(fileID) {
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: res => {
        console.log(res)
        const tempFileURL = res.fileList[0].tempFileURL
        this.updateAvatar(tempFileURL)
      }
    })
  },

  chooseAvatar(e) {
    console.log(e)
    const _openid = wx.getStorageSync('openid')
    this.upLoadAvatar(e.detail.avatarUrl, _openid)
  },

  async updateAvatar(tempFileURL) {
    const _openid = wx.getStorageSync('openid')
    await db.collection('user').where({
      _openid: _openid
    }).update({
      data: {
        avatarUrl: tempFileURL
      },
      success:  (res) => {
        console.log(res)
        this.getAvatar()
      }
    })
  },

  async getAvatar() {
    const _openid = wx.getStorageSync('openid')
    const res = await db.collection('user').where({
      _openid: _openid
    }).get()
    console.log(res)
    this.setData({
      avatarUrl:res.data[0].avatarUrl
    })
    wx.setStorageSync('avatarUrl', res.data[0].avatarUrl)
  },

  async onShow() {
    const user = await this.userIsexist()
    this.calculation()
    if (this.data.nickName === '无名氏') {
      wx.getStorageSync('userInfoResult')
      this.setData({
        nickName: `粑粑${user.userInfoResult.data.length >= 10 ? user.userInfoResult.data.length : '0' + user.userInfoResult.data.length}号`
      });
    }
    console.log(user)
    const record = {
      avatarUrl: this.data.avatarUrl,
      babaMinutes: this.data.babaMinutes,
      babaTimes: this.data.babaTimes,
      userId: 'sdsd',
      userName: this.data.nickName,
    }
    if (user.data.length == 0) {
      const existingUser = await db.collection('user').where({
        _openid: user.openid // 根据 openid 查询用户是否已存在
      }).get();
      if (existingUser.data.length == 0) { // 如果用户不存在，才插入记录
        db.collection('user').add({
          data: record,
          success: res => {
            console.log(res);
            let userInfoResult = wx.getStorageSync('userInfoResult') || { data: [] };
            userInfoResult.data.push(record);
            wx.setStorageSync('userInfoResult', userInfoResult);
          },
          fail: e => {
            console.log(e);
          }
        });
      }
    }

    const existingUser = await db.collection('user').where({
      _openid: user.openid // 根据 openid 查询用户是否已存在
    }).get();
    console.log(existingUser)
    this.setData({
      avatarUrl: existingUser.data[0].avatarUrl,
      nickName: existingUser.data[0].userName,
      qianMing: existingUser.data[0].qianMing,
    })
  },

  async onLoad() {
    const user = await this.userIsexist()
    const existingUser = await db.collection('user').where({
      _openid: user.openid // 根据 openid 查询用户是否已存在
    }).get();
    console.log(existingUser)
    this.setData({
      avatarUrl: existingUser.data[0].avatarUrl,
      nickName: existingUser.data[0].userName,
      qianMing: existingUser.data[0].qianMing,
    })
  },

  navateToEditMsg(){
    wx.navigateTo({
     url: '/pages/editMsgPage/editMsgPage?nickName='+this.data.nickName+'&qianMing='+this.data.qianMing,
    })
  },
});